package com.hongxun.design.ui.dragview.gridview_custom;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Vibrator;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.RelativeLayout;

import com.facebook.drawee.view.SimpleDraweeView;
import com.hongxun.design.MyApp;
import com.hongxun.design.bean.PhotoPassagewayItemBean;
import com.hongxun.design.constant.Constant;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.ui.dragview.AddDragIcon;
import com.hongxun.design.ui.dragview.ImageTextItem;
import com.hongxun.design.utils.DensityUtil;
import com.hongxun.design.utils.imageutil.UriUtil;

import java.util.LinkedList;
import java.util.List;


/**
 * @author xiaanming
 * @blog http://blog.csdn.net/xiaanming
 */
public class DragGridView extends GridView {
    private long dragResponseMS = 100;
    private boolean isdragResponseMS = false;
    public boolean isDrag = false;
    private int mDownX;
    private int mDownY;
    private int moveX;
    private int moveY;
    private int mDragPosition;
    private View mStartDragItemView = null;
    private SimpleDraweeView mDragImageView;
    private Vibrator mVibrator;
    private WindowManager mWindowManager;
    private WindowManager.LayoutParams mWindowLayoutParams;
    private String mDragBitmap;
    private int mPoint2ItemTop;
    private int mPoint2ItemLeft;
    private int mOffset2Top;
    private int mOffset2Left;
    private int mStatusHeight;
    private int mDownScrollBorder;
    private int mUpScrollBorder;
    private static final int speed = 20;
    private boolean mAnimationEnd = true;
    private int mNumColumns;
    private int mColumnWidth;
    private boolean mNumColumnsSet;
    private int mHorizontalSpacing;
    private Context context;

    public DragGridView(Context context) {
        this(context, null);
        this.context = context;
    }

    public DragGridView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
        this.context = context;
    }

    public DragGridView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
        mVibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        mStatusHeight = getStatusHeight(context);

        if (!mNumColumnsSet) {
            mNumColumns = AUTO_FIT;
        }
    }

    private Handler mHandler = new Handler();

    private Runnable mLongClickRunnable = new Runnable() {

        @Override
        public void run() {
            isDrag = true;
            createDragImage(mDragBitmap, mDownX, mDownY);
        }
    };

    public void setIsDrag(Boolean isDrag) {
        this.isDrag = isDrag;
    }

    @Override
    public void setNumColumns(int numColumns) {
        super.setNumColumns(numColumns);
        mNumColumnsSet = true;
        this.mNumColumns = numColumns;
    }

    @Override
    public void setColumnWidth(int columnWidth) {
        super.setColumnWidth(columnWidth);
        mColumnWidth = columnWidth;
    }

    @Override
    public void setHorizontalSpacing(int horizontalSpacing) {
        super.setHorizontalSpacing(horizontalSpacing);
        this.mHorizontalSpacing = horizontalSpacing;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mNumColumns == AUTO_FIT) {
            int numFittedColumns;
            if (mColumnWidth > 0) {
                int gridWidth = Math.max(MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft()
                        - getPaddingRight(), 0);
                numFittedColumns = gridWidth / mColumnWidth;
                if (numFittedColumns > 0) {
                    while (numFittedColumns != 1) {
                        if (numFittedColumns * mColumnWidth + (numFittedColumns - 1)
                                * mHorizontalSpacing > gridWidth) {
                            numFittedColumns--;
                        } else {
                            break;
                        }
                    }
                } else {
                    numFittedColumns = 1;
                }
            } else {
                numFittedColumns = 2;
            }
            mNumColumns = numFittedColumns;
        }
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);

    }

    public void setDragResponseMS(long dragResponseMS) {
        this.dragResponseMS = dragResponseMS;
    }

    private Boolean flag = false;

    public void getfirst(Boolean flag) {
        this.flag = flag;
    }

    PhotoPassagewayItemBean bean;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (Drag) {
            switch (ev.getAction()) {
                case MotionEvent.ACTION_DOWN:

                    if (!flag) {
                        onStopDrag();
                        mDownX = (int) ev.getX();
                        mDownY = (int) ev.getY();
                        mDragPosition = pointToPosition(mDownX, mDownY);
                        if (mDragPosition == AdapterView.INVALID_POSITION) {
                            return super.dispatchTouchEvent(ev);
                        }

                        mHandler.postDelayed(mLongClickRunnable, dragResponseMS);
                        mStartDragItemView = getChildAt(mDragPosition - getFirstVisiblePosition());
                        mPoint2ItemTop = mDownY - mStartDragItemView.getTop();
                        mPoint2ItemLeft = mDownX - mStartDragItemView.getLeft();
                        mOffset2Top = (int) (ev.getRawY() - mDownY);
                        mOffset2Left = (int) (ev.getRawX() - mDownX);
                        mDownScrollBorder = getHeight() / 5;
                        mUpScrollBorder = getHeight() * 4 / 5;
                        mStartDragItemView.setDrawingCacheEnabled(true);
                        mDragBitmap = ((ImageTextItem) mStartDragItemView).getIconTouch();
                        bean = ((ImageTextItem) mStartDragItemView).getItemBean();
                        mStartDragItemView.destroyDrawingCache();
                    } else {
                        flag = false;
                    }
                    break;
                case MotionEvent.ACTION_MOVE:

                    int moveX = (int) ev.getX();
                    int moveY = (int) ev.getY();
                    if (!isTouchInItem(mStartDragItemView, moveX, moveY)) {
                        mHandler.removeCallbacks(mLongClickRunnable);
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    mHandler.removeCallbacks(mLongClickRunnable);
                    mHandler.removeCallbacks(mScrollRunnable);
                    break;
            }
        } else {
            if (!MyApp.ReadOnly) {
                ToastShow.showShort(context, "上级级联不存在！");
            }

        }

        return super.dispatchTouchEvent(ev);
    }

    private boolean isTouchInItem(View dragView, int x, int y) {
        if (dragView == null) {
            return false;
        }
        int leftOffset = dragView.getLeft();
        int topOffset = dragView.getTop();
        if (x < leftOffset || x > leftOffset + dragView.getWidth()) {
            return false;
        }
        return !(y < topOffset || y > topOffset + dragView.getHeight());
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {

        if (Drag && isDrag && mDragImageView != null) {
            switch (ev.getAction()) {
                case MotionEvent.ACTION_MOVE:
                    moveX = (int) ev.getX();
                    moveY = (int) ev.getY();
                    getParent().requestDisallowInterceptTouchEvent(true);
                    onDragItem(moveX, moveY);
                    break;
                case MotionEvent.ACTION_UP:
                    int[] s = new int[2];
                    line.getLocationOnScreen(s);
                    int[] s2 = new int[2];
                    mDragImageView.getLocationOnScreen(s2);

                    if (s[1] - line.getHeight() < s2[1] && s[1] + line.getHeight() > s2[1] && !(s2[0] + mDragImageView.getWidth() < s[0] || s2[0] > s[0] + line.getWidth())) {
                        mWindowLayoutParams.width = DensityUtil.dip2px(context, 24);
                        mWindowLayoutParams.height = DensityUtil.dip2px(context, 24);
                        mWindowManager.updateViewLayout(mDragImageView, mWindowLayoutParams);
                        if (s2[0] + mDragImageView.getWidth() > s[0] + line.getWidth()) {
                            s2[0] = s[0] + line.getWidth() - mDragImageView.getWidth();
                        }

//                        bean.setXy(new int[]{s2[0] - mDragImageView.getWidth() / 2, (int) s[1] + mDragImageView.getHeight() / 2});
                        int x = s2[0] - mDragImageView.getWidth() / 2;
                        if (x < 0) {
                            x = 0;
                        }
                        bean.setXy(new int[]{x, ViewY});

                        AddDragIcon dragIcon = new AddDragIcon();
                        bean.setDistance((x * Level) + "");
                        MyLog.L(MString.SUCCESSED + "  bean.setDistance=" + (x * Level));
                        dragIcon.setData(bean, context, container, Constant.TYPE_GRID);

                    }
                    isDrag = true;
                    onStopDrag();

                    break;
            }
            return true;
        }
        return super.onTouchEvent(ev);
    }


    private View line;
    RelativeLayout container;
    int ViewY;
    boolean Drag = true;

    public void setLine(View v, RelativeLayout container, int Y, boolean Drag) {
        this.line = v;
        this.container = container;
        this.ViewY = Y;
        this.Drag = Drag;

    }

    /**
     * 设置比例尺*
     */
    public float Level = (float) 1.0;

    public void setLevel(float Level) {
        this.Level = Level;
    }

    private void createDragImage(String bitmap, int downX, int downY) {
        if (isDrag) {
            mWindowLayoutParams = new WindowManager.LayoutParams();
            mWindowLayoutParams.format = PixelFormat.TRANSLUCENT;
            mWindowLayoutParams.gravity = Gravity.TOP | Gravity.LEFT;
            mWindowLayoutParams.x = downX - mPoint2ItemLeft + mOffset2Left;
            mWindowLayoutParams.y = downY - mPoint2ItemTop + mOffset2Top - mStatusHeight;
            mWindowLayoutParams.alpha = 0.55f;
            mWindowLayoutParams.width = DensityUtil.dip2px(context, 40);
            mWindowLayoutParams.height = DensityUtil.dip2px(context, 40);
            mWindowLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                    | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
            mDragImageView = new SimpleDraweeView(getContext());
            mDragImageView.setImageURI(UriUtil.getUri(bitmap));
            mWindowManager.addView(mDragImageView, mWindowLayoutParams);
        }

    }

    private void removeDragImage() {
        if (mDragImageView != null) {
            mWindowManager.removeView(mDragImageView);
            mDragImageView.setVisibility(GONE);
            mDragImageView = null;
        }
    }

    private void onDragItem(int moveX, int moveY) {
        mWindowLayoutParams.x = moveX - mPoint2ItemLeft + mOffset2Left;
        mWindowLayoutParams.y = moveY - mPoint2ItemTop + mOffset2Top - mStatusHeight;
        mWindowManager.updateViewLayout(mDragImageView, mWindowLayoutParams); //
        // onSwapItem(moveX, moveY);
        mHandler.post(mScrollRunnable);
    }

    private Runnable mScrollRunnable = new Runnable() {

        @Override
        public void run() {
            int scrollY;
            if (getFirstVisiblePosition() == 0 || getLastVisiblePosition() == getCount() - 1) {
                mHandler.removeCallbacks(mScrollRunnable);
            }

            if (moveY > mUpScrollBorder) {
                scrollY = speed;
                mHandler.postDelayed(mScrollRunnable, 25);
            } else if (moveY < mDownScrollBorder) {
                scrollY = -speed;
                mHandler.postDelayed(mScrollRunnable, 25);
            } else {
                scrollY = 0;
                mHandler.removeCallbacks(mScrollRunnable);
            }

            smoothScrollBy(scrollY, 10);
        }
    };

    private void onSwapItem(int moveX, int moveY) {
        final int tempPosition = pointToPosition(moveX, moveY);
        if (tempPosition != mDragPosition && tempPosition != AdapterView.INVALID_POSITION && mAnimationEnd) {

            final ViewTreeObserver observer = getViewTreeObserver();
            observer.addOnPreDrawListener(new OnPreDrawListener() {
                @Override
                public boolean onPreDraw() {
                    observer.removeOnPreDrawListener(this);
                    animateReorder(mDragPosition, tempPosition);
                    mDragPosition = tempPosition;
                    return true;
                }
            });

        }
    }

    @SuppressLint("NewApi")
    private AnimatorSet createTranslationAnimations(View view, float startX,
                                                    float endX, float startY, float endY) {
        ObjectAnimator animX = ObjectAnimator.ofFloat(view, "translationX",
                startX, endX);
        ObjectAnimator animY = ObjectAnimator.ofFloat(view, "translationY",
                startY, endY);
        AnimatorSet animSetXY = new AnimatorSet();
        animSetXY.playTogether(animX, animY);
        return animSetXY;
    }

    @SuppressLint("NewApi")
    private void animateReorder(final int oldPosition, final int newPosition) {
        boolean isForward = newPosition > oldPosition;
        List<Animator> resultList = new LinkedList<Animator>();
        if (isForward) {
            for (int pos = oldPosition; pos < newPosition; pos++) {
                View view = getChildAt(pos - getFirstVisiblePosition());
                System.out.println(pos);

                if ((pos + 1) % mNumColumns == 0) {
                    resultList.add(createTranslationAnimations(view,
                            -view.getWidth() * (mNumColumns - 1), 0,
                            view.getHeight(), 0));
                } else {
                    resultList.add(createTranslationAnimations(view,
                            view.getWidth(), 0, 0, 0));
                }
            }
        } else {
            for (int pos = oldPosition; pos > newPosition; pos--) {
                View view = getChildAt(pos - getFirstVisiblePosition());
                if ((pos + mNumColumns) % mNumColumns == 0) {
                    resultList.add(createTranslationAnimations(view,
                            view.getWidth() * (mNumColumns - 1), 0,
                            -view.getHeight(), 0));
                } else {
                    resultList.add(createTranslationAnimations(view,
                            -view.getWidth(), 0, 0, 0));
                }
            }
        }

        AnimatorSet resultSet = new AnimatorSet();
        resultSet.playTogether(resultList);
        resultSet.setDuration(300);
        resultSet.setInterpolator(new AccelerateDecelerateInterpolator());
        resultSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                mAnimationEnd = false;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                mAnimationEnd = true;
            }
        });
        resultSet.start();
    }

    public void onStopDrag() {
        View view = getChildAt(mDragPosition - getFirstVisiblePosition());
        if (view != null) {
            view.setVisibility(View.VISIBLE);
        }
        removeDragImage();
    }

    private static int getStatusHeight(Context context) {
        int statusHeight = 0;
        Rect localRect = new Rect();
        ((Activity) context).getWindow().getDecorView().getWindowVisibleDisplayFrame(localRect);
        statusHeight = localRect.top;
        if (0 == statusHeight) {
            Class<?> localClass;
            try {
                localClass = Class.forName("com.android.internal.R$dimen");
                Object localObject = localClass.newInstance();
                int i5 = Integer.parseInt(localClass.getField("status_bar_height").get(localObject).toString());
                statusHeight = context.getResources().getDimensionPixelSize(i5);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return statusHeight;
    }

}
